package com.hp.ssmp.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hp.ssmp.entity.TGoods;
import com.hp.ssmp.entity.TUser;
import com.hp.ssmp.service.GoodsService;
import com.hp.ssmp.util.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
@RequestMapping("/goods")
public class GoodsController {
    @Autowired
    private RedisTemplate<String,Object> redisTemplate;

    @Autowired
    private GoodsService goodsService;

    /**
     * @description: 获取推广商品
     * @param: [type 1：今日特价 2：热卖推荐 , count 商品数量]
     * @return: java.util.List<com.hp.entity.Goods>
     **/
    @GetMapping("/getPromotionGoods")
    public List<TGoods> getPromotionGoods(Long type, Long count){
        List<TGoods> goodsList = null;
        if(redisTemplate.hasKey("PromotionGoods_"+type)){
            goodsList = (List<TGoods>)
                    redisTemplate.opsForValue().get("PromotionGoods_"+type);
        }else{
            goodsList = goodsService.getPromotionGoods(type, count);
            redisTemplate.opsForValue().set("PromotionGoods_"+type, goodsList);
        }
        return goodsList;
    }

    /**
     * 分页条件查询商品
     * @param currentPage
     * @param pageSize
     * @param categoryid
     * @return
     */
    @GetMapping("/getListPage")
    public R<Page<TGoods>> page(Integer currentPage, Integer pageSize, Long categoryid,Long level) {
        Page<TGoods> userPage = goodsService.getGoodsPage(currentPage, pageSize, categoryid,level);
        return R.success(userPage);
    }

    @GetMapping("/getById")
    public R getGoodsById(Long goodsid) {
        TGoods goods = goodsService.getById(goodsid);
        return R.success(goods);
    }

    /**
     * 根据id删除商品
     * @param goodsid
     * @return
     */
    @GetMapping("/del")
    public R delGoods(Long goodsid) {
        boolean result = goodsService.removeById(goodsid);
        if (result) {
            return R.success();
        } else {
            return R.error();
        }
    }

    /**
     * 新增商品
     * @param goods
     * @return
     */
    @PostMapping("/add")
    public R add(TGoods goods) {
        goods.setGoodsstatus(1L);
        boolean result = goodsService.save(goods);
        if (result) {
            return R.success();
        } else {
            return R.error();
        }
    }

    @PostMapping("/update")
    public R update(TGoods goods) {
        System.out.println(goods.toString());
        boolean result = goodsService.updateById(goods);
        if (result) {
            return R.success();
        } else {
            return R.error();
        }
    }
}
